package com.jic.order.impl;

import com.alibaba.fastjson.JSON;
import com.jic.common.base.vo.RestResult;
import com.jic.common.utils.IDUtils;
import com.jic.market.api.after.CouponApi;
import com.jic.market.api.after.GrouponApi;
import com.jic.member.api.rest.MemberDistributorApi;
import com.jic.member.api.rest.MemberInformationApi;
import com.jic.member.request.CommissionInfoResquest;
import com.jic.member.request.MeinformationRequest;
import com.jic.order.entity.*;
import com.jic.order.enums.OperatorActionEnum;
import com.jic.order.enums.OrderEnum;
import com.jic.order.exception.OrderException;
import com.jic.order.mapper.*;
import com.jic.order.model.OrderModel;
import com.jic.order.model.ParentOrderModel;
import com.jic.order.model.domain.BuyerModel;
import com.jic.order.model.domain.OperateModel;
import com.jic.order.model.domain.OrderBaleModel;
import com.jic.order.model.domain.OrderDeliverModel;
import com.jic.order.model.domain.OrderGoodsModel;
import com.jic.order.model.domain.SellerModel;
import com.jic.order.request.OrderRouteSplitWarehouseRequest;
import com.jic.order.response.OrderRouteSplitWarehouseResponse;
import com.jic.order.service.ModelService;
import com.jic.product.after.api.ProductListApi;
import com.jic.product.after.request.ProductSaleNumRequest;
import com.jic.product.after.response.ProductAfterInfoByIdResponse;
import com.jic.product.store.MStoreApi;
import com.jic.product.store.request.MStoreFrozenRequest;
import com.jic.product.store.request.MStoreQueryRequest;
import com.jic.product.store.request.MStoreSubmitRequest;
import com.jic.product.store.response.MStoreResponse;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class ModelServiceImpl implements ModelService {

    @Autowired
    private OrderParentMapper orderParentMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderGoodsMapper orderGoodsMapper;
    @Autowired
    private OrderDeliverMapper orderDeliverMapper;
    @Autowired
    private OrderDeliverDetailMapper orderDeliverDetailMapper;
    @Autowired
    private OrderProcessLogMapper orderProcessLogMapper;
    @Autowired
    private OrderBaleMapper orderBaleMapper;
    @Autowired
    private OrderInvoiceMapper orderInvoiceMapper;
    @Autowired
    private OrderBaleDetailMapper orderBaleDetailMapper;
    @Autowired
    private OrderRouteSplitWarehouseMapper orderRouteSplitWarehouseMapper;

    @Resource
    private ProductListApi productListApi;
    @Resource
    private MemberDistributorApi memberDistributorApi;
    @Resource
    private CouponApi couponRestApi;
    @Resource
    private GrouponApi grouponRestApi;
    @Resource
    private MStoreApi mStoreApi;
    @Resource
    private MemberInformationApi memberInformationApi;

    @Resource
    private OrderAutomaticCancelMapper orderAutomaticCancelMapper;

    @Override
    public void fillParentOrder(ParentOrderModel parentOrderModel) {
        //无parentOrderNo，表示是新订单
        if (null == parentOrderModel.getParentOrderNo()) {
            //生成一个父订单号
            String parentOrderNo = IDUtils.GenerateBillNo();
            parentOrderModel.setParentOrderNo(parentOrderNo);
        }
        //有parentOrderNo，表示是旧订单
        else {
            OrderParent orderParentQ = new OrderParent();
            orderParentQ.setParentOrderNo(parentOrderModel.getParentOrderNo());
            List<OrderParent> orderParentList = orderParentMapper.query(orderParentQ);
            if (null == orderParentList || orderParentList.isEmpty()) {
                log.info("该父订单号无数据");
                throw new OrderException(OrderEnum.DATA_EXECEPTION, "该父订单号无数据");
            }
            convertModel(orderParentList.get(0), parentOrderModel);
            Order orderQ = new Order();
            orderQ.setParentOrderNo(parentOrderModel.getParentOrderNo());
            List<Order> orderList = orderMapper.query(orderQ);
            if (null != orderList && !orderList.isEmpty()) {
                for (Order order : orderList) {
                    OrderModel orderModel = new OrderModel();
                    fillOrderModel(order, orderModel);
                    parentOrderModel.getOrderModelList().add(orderModel);
                }
            }

        }
    }

    @Override
    public void fillOrder(OrderModel orderModel) {
        if (null == orderModel.getOrderNo()) {
            log.info("订单号为空");
            throw new OrderException(OrderEnum.ORDER_NO_IS_NULL_EXECEPTION, "订单号为空");
        }
        Order orderQ = new Order();
        orderQ.setOrderNo(orderModel.getOrderNo());
        List<Order> orderList = orderMapper.query(orderQ);
        if (null == orderList || orderList.isEmpty()) {
            log.info("该订单号无数据");
            throw new OrderException(OrderEnum.DATA_EXECEPTION, "该订单号无数据");
        }
        Order order = orderList.get(0);
        fillOrderModel(order, orderModel);
    }

    private void fillOrderModel(Order order, OrderModel orderModel) {
        BeanUtils.copyProperties(order, orderModel);

        BuyerModel buyerModel = new BuyerModel();
        buyerModel.setBuyerId(order.getBuyerId());
        buyerModel.setBuyerUsername(order.getBuyerUsername());
        buyerModel.setBuyerRealname(order.getBuyerRealname());
        orderModel.setBuyerModel(buyerModel);

        SellerModel sellerModel = new SellerModel();
        BeanUtils.copyProperties(order, sellerModel);
        orderModel.setSellerModel(sellerModel);

        // 加载交货单
        OrderDeliver orderDeliverQ = new OrderDeliver();
        orderDeliverQ.setOrderNo(orderModel.getOrderNo());
        List<OrderDeliver> orderDeliverList = orderDeliverMapper.query(orderDeliverQ);
        if (null != orderDeliverList && !orderDeliverList.isEmpty()) {
            for (OrderDeliver orderDeliver : orderDeliverList) {
                OrderDeliverModel orderDeliverModel = convertModel(orderDeliver, new OrderDeliverModel());
                orderModel.getOrderDeliverModelList().add(orderDeliverModel);
            }
        }

        // 加载商品
        OrderGoods orderGoodsQ = new OrderGoods();
        orderGoodsQ.setOrderNo(orderModel.getOrderNo());
        List<OrderGoods> orderGoodsList = orderGoodsMapper.query(orderGoodsQ);
        if (null != orderGoodsList && !orderGoodsList.isEmpty()) {
            for (OrderGoods orderGoods : orderGoodsList) {
                OrderGoodsModel orderGoodsModel = convertModel(orderGoods);
                orderModel.getOrderGoodsModelList().add(orderGoodsModel);
            }
        }
    }

    @Override
    public void fillDeliver(OrderDeliverModel orderDeliverModel) {
        if (null == orderDeliverModel.getDeliverNo()) {
            log.info("交货单号为空");
            throw new OrderException(OrderEnum.DELIVER_NO_IS_NULL_EXECEPTION, "交货单号为空");
        }
        OrderDeliver orderDeliverQ = new OrderDeliver();
        orderDeliverQ.setDeliverNo(orderDeliverModel.getDeliverNo());
        List<OrderDeliver> orderDeliverList = orderDeliverMapper.query(orderDeliverQ);
        if (null == orderDeliverList || orderDeliverList.isEmpty()) {
            log.info("该交货单号无数据");
            throw new OrderException(OrderEnum.DATA_EXECEPTION, "该交货单号无数据");
        }
        convertModel(orderDeliverList.get(0), orderDeliverModel);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveParentOrder(ParentOrderModel parentOrderModel, OperateModel operateModel) {
        //insert操作
        if (0 == parentOrderModel.getId()) {
            OrderParent orderParent = new OrderParent();
            BeanUtils.copyProperties(parentOrderModel, orderParent);
            // 是否分销员 1.是 2.否
//			Long id = orderParent.getBuyerId();
//			RestResult<MemberStatus> restResult = memberDistributorApi.queryDistributorById(id);
//			if (restResult.getData() != null) {
//				orderParent.setBuyerType(restResult.getData().getStatus());
//			}
            orderParent.setVersion(1);
            orderParent.setCreator(operateModel.getOperator());
            orderParent.setCreateName(operateModel.getOperatorName());
            orderParent.setCreateTime(operateModel.getOperatorTime());
            // 设置支付过期时间，读取自动取消配置
            OrderAutomaticCancel orderAutomaticCancel = orderAutomaticCancelMapper.queryOrderCancel();
            Long cancelTime = 30L;// 默认30分钟
            if (orderAutomaticCancel != null){
                cancelTime = orderAutomaticCancel.getCancelTime();
            }
            Date paymentExpire = new Date(operateModel.getOperatorTime().getTime() + (cancelTime * 60 * 1000));
            orderParent.setPaymentExpire(paymentExpire);
//            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy:MM:dd hh:mm:ss");
//            String format = dateFormat.format(paymentExpire);
//
//
//            try {
//                orderParent.setPaymentExpire(dateFormat.parse(format));
//            } catch (ParseException e) {
//                log.error("parse paymentExpire is error",e);
//            }
            orderParentMapper.insert(orderParent);
        }
        //update操作
        else {
            OrderParent orderParent = new OrderParent();
            BeanUtils.copyProperties(parentOrderModel, orderParent);
            orderParent.setVersion(orderParent.getVersion() + 1);
            orderParent.setUpdater(operateModel.getOperator());
            orderParent.setUpdaterName(operateModel.getOperatorName());
            orderParent.setUpdateTime(operateModel.getOperatorTime());
            orderParentMapper.update(orderParent);
        }
        //保存子订单
        List<OrderModel> orderModelList = parentOrderModel.getOrderModelList();
        if (null != orderModelList && !orderModelList.isEmpty()) {
            for (OrderModel orderModel : orderModelList) {
                saveOrder(orderModel, operateModel);
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrder(OrderModel orderModel, OperateModel operateModel) {
        RestResult<ProductAfterInfoByIdResponse> getDeptId = productListApi.queryProductInfoById(orderModel.getOrderGoodsModelList().get(0).getGoodsId());
        if (0 == orderModel.getId()) {
            //TODO 调用优惠券
            //			UseCouponRequest useCouponRequest = new UseCouponRequest();
            //			useCouponRequest.setUserId(userId);
            //			useCouponRequest.setCouponCode(request.getPromotionId());
            //			useCouponRequest.setOrderCode(orderParent.getParentOrderNo());
            //			RestResult<Boolean> booleanRestResult1 = couponRestApi.useCoupons(useCouponRequest);
            //			if ("9999".equals(booleanRestResult.getCode())) {
            //				return RestResult.error("9999", booleanRestResult1.getMsg());
            //			}

            Order order = convert(orderModel);
            order.setVersion(1);
            order.setDeptId(getDeptId.getData().getDeptId());
            order.setCreator(operateModel.getOperator());
            order.setCreatorName(operateModel.getOperatorName());
            order.setCreateTime(operateModel.getOperatorTime());
            if (orderModel.getProductType() != null){
                order.setOrderType(orderModel.getProductType());
            }
            orderMapper.insert(order);
        } else {
            Order order = convert(orderModel);
            order.setVersion(order.getVersion() + 1);
            order.setUpdater(operateModel.getOperator());
            order.setUpdaterName(operateModel.getOperatorName());
            order.setUpdateTime(operateModel.getOperatorTime());
            orderMapper.update(order);
        }

        //商品明细
        List<OrderGoodsModel> orderGoodsModels = orderModel.getOrderGoodsModelList();
        ProductSaleNumRequest productSaleNumRequest = new ProductSaleNumRequest();
        List<ProductSaleNumRequest> productSaleNumRequestList = new ArrayList<>();
        if (null != orderGoodsModels && !orderGoodsModels.isEmpty()) {
            for (OrderGoodsModel orderGoodsModel : orderGoodsModels) {
                if (0 == orderGoodsModel.getId()) {
                    OrderGoods orderGoods = convert(orderGoodsModel, orderModel);
                    orderGoods.setVersion(1);
                    orderGoods.setCreator(operateModel.getOperator());
                    orderGoods.setCreateName(operateModel.getOperatorName());
                    orderGoods.setCreateTime(operateModel.getOperatorTime());
                    //判断分享商品是不是自已购买
                    if (orderGoodsModel.getDistributorId() != null && orderModel.getBuyerModel().getBuyerId() != orderGoodsModel.getDistributorId()) {
                        orderGoods.setDistributorId(orderGoodsModel.getDistributorId());
                    }else {
                        orderGoods.setDistributorId(null);
                    }
                    orderGoods.setCardPhone(orderGoodsModel.getVirtualPhone());
                    orderGoodsMapper.insert(orderGoods);

                    // 订单付款消息推送
                    MeinformationRequest meinformationRequest = new MeinformationRequest();
                    meinformationRequest.setMemberId(operateModel.getOperator());
                    meinformationRequest.setType(1);
                    meinformationRequest.setTitle("您购买的" + orderGoods.getGoodsName() + "等待付款,请及时付款,以免错失商品");
                    meinformationRequest.setCategory(1);
                    memberInformationApi.insertMemberInformation(meinformationRequest);
                    if (orderGoodsModel.getGroupType() != null) {
                        // 调用开团接口
                        this.spellGroupInterface(orderModel, orderGoodsModel);
                    }

                    ProductSaleNumRequest productSaleNumRequest1 = new ProductSaleNumRequest();
                    productSaleNumRequest1.setProductId(orderGoods.getGoodsId());
                    productSaleNumRequest1.setSaleNum(Long.valueOf(orderGoods.getGoodsNum()));
                    productSaleNumRequestList.add(productSaleNumRequest1);

                    //调用冻结库存接口
                    this.frozenStock(orderGoods, orderGoodsModel.getSellerModel());
                } else {
                    OrderGoods orderGoodsOrigin = orderGoodsMapper.queryByPrimaryKey(orderGoodsModel.getId());
                    //当前数据版本号已经被更改，抛出异常回滚数据
                    if (orderGoodsOrigin.getVersion() > orderGoodsModel.getVersion()) {
                        log.info("当前数据（OrderGoods）已经被更改，原数据orderGoods={}", JSON.toJSONString(orderGoodsOrigin));
                        throw new OrderException(OrderEnum.DATA_VERSION_EXECEPTION, "当前数据（OrderGoods）已经被更改");
                    }
                    OrderGoods orderGoods = convert(orderGoodsModel, orderModel);
                    orderGoods.setVersion(orderGoods.getVersion() + 1);
                    orderGoods.setUpdater(operateModel.getOperator());
                    orderGoods.setUpdateName(operateModel.getOperatorName());
                    orderGoods.setUpdateTime(operateModel.getOperatorTime());
                    orderGoodsMapper.update(orderGoods);
                }
            }
        }
        productSaleNumRequest.setProductSaleNumRequestList(productSaleNumRequestList);
        productListApi.updateProductSaleNum(productSaleNumRequest);
        //交货单
        List<OrderDeliverModel> orderDeliverModels = orderModel.getOrderDeliverModelList();
        if (null != orderDeliverModels && !orderDeliverModels.isEmpty()) {
            for (OrderDeliverModel orderDeliverModel : orderDeliverModels) {
                save(orderDeliverModel, operateModel);
            }
        }

        //联动改订单状态和父订单状态
        if (operateModel.getOperatorAction() == OperatorActionEnum.CLOSED ||
                operateModel.getOperatorAction() == OperatorActionEnum.DELIVER ||
                operateModel.getOperatorAction() == OperatorActionEnum.AUDIT ||
                operateModel.getOperatorAction() == OperatorActionEnum.MODIFY_ORDER_STATUS) {
            coupUpdateParentOrderStatus(orderModel.getParentOrderNo());
        }

        //操作日志
        OrderProcessLog orderProcessLog = convert(operateModel);
        orderProcessLog.setOrderNo(orderModel.getOrderNo());
        orderProcessLogMapper.insert(orderProcessLog);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveDeliver(OrderDeliverModel orderDeliverModel, OperateModel operateModel) {
        save(orderDeliverModel, operateModel);
        //操作日志
        OrderProcessLog orderProcessLog = convert(operateModel);
        orderProcessLog.setOrderNo(orderDeliverModel.getOrderNo());
        orderProcessLogMapper.insert(orderProcessLog);
    }

    @Override
    public void coupUpdateOrderStatus(String orderNo) {
        //联动交货单到子订单
        //update m_order set order_status=(select DISTINCT order_status from m_order_deliver where order_no='O2020012412275604310600003') where order_no='O2020012412275604310600003';
        //此时更新就不加悲观锁了
        orderMapper.coupUpdateOrderStatus(orderNo);
    }

    @Override
    public void coupUpdateParentOrderStatus(String parentOrderNo) {
        //联动子订单到父订单
        //此时更新就不加悲观锁了
        orderMapper.coupUpdateParentOrderStatus(parentOrderNo);
    }

    private void save(OrderDeliverModel orderDeliverModel, OperateModel operateModel) {
        //insert操作
        if (0 == orderDeliverModel.getId()) {
            OrderDeliver orderDeliver = convert(orderDeliverModel);
            orderDeliver.setOrderNo(orderDeliverModel.getOrderNo());
            orderDeliver.setVersion(1);
            orderDeliver.setCreator(operateModel.getOperator());
            orderDeliver.setCreatorName(operateModel.getOperatorName());
            orderDeliver.setCreateTime(operateModel.getOperatorTime());
            orderDeliverMapper.insert(orderDeliver);
        }
        //update操作
        else {
            OrderDeliver orderDeliverOrigin = orderDeliverMapper.queryByPrimaryKey(orderDeliverModel.getId());
            if (orderDeliverOrigin.getVersion() > orderDeliverModel.getVersion()) {
                log.info("当前数据（OrderDeliver）已经被更改，原数据orderDeliverOrigin={}", JSON.toJSONString(orderDeliverOrigin));
                throw new OrderException(OrderEnum.DATA_VERSION_EXECEPTION, "当前数据（OrderDeliver）已经被更改");
            }
            OrderDeliver orderDeliver = convert(orderDeliverModel);
            orderDeliver.setOrderNo(orderDeliverModel.getOrderNo());
            orderDeliver.setVersion(orderDeliver.getVersion() + 1);
            orderDeliver.setUpdater(operateModel.getOperator());
            orderDeliver.setUpdaterName(operateModel.getOperatorName());
            orderDeliver.setUpdateTime(operateModel.getOperatorTime());
            orderDeliverMapper.update(orderDeliver);
        }
        //联动改订单状态和父订单状态
        try {
            if (operateModel.getOperatorAction() == OperatorActionEnum.DELIVER
                    || operateModel.getOperatorAction() == OperatorActionEnum.SEND_GOODS
                    || operateModel.getOperatorAction() == OperatorActionEnum.AUDIT) {
                coupUpdateOrderStatus(orderDeliverModel.getOrderNo());
                Order orderQ = new Order();
                orderQ.setOrderNo(orderDeliverModel.getOrderNo());
                List<Order> orderList = orderMapper.query(orderQ);
                if (null != orderList && !orderList.isEmpty()) {
                    coupUpdateParentOrderStatus(orderList.get(0).getParentOrderNo());
                }
            }
        } catch (Exception e) {

        }
        saveOrderDeliverDetail(orderDeliverModel, operateModel);
        saveOrderBale(orderDeliverModel, operateModel);
    }

    private void saveOrderDeliverDetail(OrderDeliverModel orderDeliverModel, OperateModel operateModel) {
        List<OrderDeliverModel.OrderDeliverDetailModel> orderDeliverDetailModelList = orderDeliverModel.getOrderDeliverDetailModelList();
        if (null != orderDeliverDetailModelList && !orderDeliverDetailModelList.isEmpty()) {
            for (OrderDeliverModel.OrderDeliverDetailModel orderDeliverDetailModel : orderDeliverDetailModelList) {
                //insert操作
                if (0 == orderDeliverDetailModel.getId()) {
                    OrderDeliverDetail orderDeliverDetail = convert(orderDeliverDetailModel);
                    orderDeliverDetail.setDeliverNo(orderDeliverModel.getDeliverNo());
                    orderDeliverDetail.setVersion(1);
                    orderDeliverDetail.setCreator(operateModel.getOperator());
                    orderDeliverDetail.setCreatorName(operateModel.getOperatorName());
                    orderDeliverDetail.setCreateTime(operateModel.getOperatorTime());
                    orderDeliverDetailMapper.insert(orderDeliverDetail);

                    //路由分仓
                    //                    this.routingPointsWarehouse(orderDeliverModel, orderDeliverDetail, operateModel);
                }
                //update操作
                else {
                    OrderDeliverDetail orderDeliverDetailOrigin = orderDeliverDetailMapper.queryByPrimaryKey(orderDeliverDetailModel.getId());
                    if (orderDeliverDetailOrigin.getVersion() > orderDeliverDetailModel.getVersion()) {
                        log.info("当前数据（OrderDeliverDetail）已经被更改，原数据orderDeliverDetailOrigin={}", JSON.toJSONString(orderDeliverDetailOrigin));
                        throw new OrderException(OrderEnum.DATA_VERSION_EXECEPTION, "当前数据（OrderDeliverDetail）已经被更改");
                    }
                    OrderDeliverDetail orderDeliverDetail = convert(orderDeliverDetailModel);
                    orderDeliverDetail.setDeliverNo(orderDeliverModel.getDeliverNo());
                    orderDeliverDetail.setVersion(orderDeliverDetail.getVersion() + 1);
                    orderDeliverDetail.setUpdater(operateModel.getOperator());
                    orderDeliverDetail.setUpdateName(operateModel.getOperatorName());
                    orderDeliverDetail.setUpdateTime(operateModel.getOperatorTime());
                    orderDeliverDetailMapper.update(orderDeliverDetail);
                }
            }
        }
    }

    private void saveOrderBale(OrderDeliverModel orderDeliverModel, OperateModel operateModel) {
        List<OrderBaleModel> orderBaleModelList = orderDeliverModel.getOrderBaleModelList();
        if (null != orderBaleModelList && !orderBaleModelList.isEmpty()) {
            for (OrderBaleModel orderBaleModel : orderBaleModelList) {
                //insert操作
                if (0 == orderBaleModel.getId()) {
                    OrderBale orderBale = new OrderBale();
                    BeanUtils.copyProperties(orderBaleModel, orderBale, "id");
                    orderBale.setVersion(1);
                    orderBale.setCreator(operateModel.getOperator());
                    orderBale.setCreatorName(operateModel.getOperatorName());
                    orderBale.setCreateTime(operateModel.getOperatorTime());
                    orderBaleMapper.insert(orderBale);
                    saveOrderBaleDetailModelList(orderBaleModel, operateModel);
                }
                //update操作
                else {
                    OrderBale orderBale = new OrderBale();
                    BeanUtils.copyProperties(orderBaleModel, orderBale);
                    orderBale.setVersion(orderBale.getVersion() + 1);
                    orderBale.setUpdater(operateModel.getOperator());
                    orderBale.setUpdaterName(operateModel.getOperatorName());
                    orderBale.setUpdateTime(operateModel.getOperatorTime());
                    orderBaleMapper.update(orderBale);
                    saveOrderBaleDetailModelList(orderBaleModel, operateModel);

                }
            }
        }
    }

    private void saveOrderBaleDetailModelList(OrderBaleModel orderBaleModel, OperateModel operateModel) {
        List<OrderBaleModel.OrderBaleDetailModel> orderBaleDetailModelList = orderBaleModel.getOrderBaleDetailModelList();
        if (null != orderBaleDetailModelList && !orderBaleDetailModelList.isEmpty()) {
            for (OrderBaleModel.OrderBaleDetailModel orderBaleDetailModel : orderBaleDetailModelList) {
                if (0 == orderBaleDetailModel.getId()) {
                    OrderBaleDetail orderBaleDetail = new OrderBaleDetail();
                    BeanUtils.copyProperties(orderBaleDetailModel, orderBaleDetail, "id");
                    orderBaleDetail.setVersion(1L);
                    orderBaleDetail.setCreator(operateModel.getOperator());
                    orderBaleDetail.setCreatorName(operateModel.getOperatorName());
                    orderBaleDetail.setCreateTime(operateModel.getOperatorTime());
                    orderBaleDetailMapper.insert(orderBaleDetail);
                } else {
                    OrderBaleDetail orderBaleDetail = new OrderBaleDetail();
                    BeanUtils.copyProperties(orderBaleDetailModel, orderBaleDetail);
                    orderBaleDetail.setVersion(orderBaleDetail.getVersion() + 1);
                    orderBaleDetail.setUpdater(operateModel.getOperator());
                    orderBaleDetail.setUpdaterName(operateModel.getOperatorName());
                    orderBaleDetail.setUpdateTime(operateModel.getOperatorTime());
                    orderBaleDetailMapper.update(orderBaleDetail);
                }
            }
        }
    }

    private OrderDeliverModel convertModel(OrderDeliver orderDeliver, OrderDeliverModel orderDeliverModel) {
        BeanUtils.copyProperties(orderDeliver, orderDeliverModel);
        SellerModel sellerModel = new SellerModel();
        BeanUtils.copyProperties(orderDeliver, sellerModel);
        orderDeliverModel.setSellerModel(sellerModel);
        //交货单明细
        OrderDeliverDetail orderDeliverDetailQ = new OrderDeliverDetail();
        orderDeliverDetailQ.setDeliverNo(orderDeliver.getDeliverNo());
        List<OrderDeliverDetail> orderDeliverDetailList = orderDeliverDetailMapper.query(orderDeliverDetailQ);
        if (null != orderDeliverDetailList && !orderDeliverDetailList.isEmpty()) {
            for (OrderDeliverDetail orderDeliverDetail : orderDeliverDetailList) {
                OrderDeliverModel.OrderDeliverDetailModel orderDeliverDetailModel = new OrderDeliverModel.OrderDeliverDetailModel();
                BeanUtils.copyProperties(orderDeliverDetail, orderDeliverDetailModel);
                orderDeliverModel.getOrderDeliverDetailModelList().add(orderDeliverDetailModel);
            }
        }
        //TODO 包裹

        return orderDeliverModel;
    }

    private OrderGoodsModel convertModel(OrderGoods orderGoods) {
        OrderGoodsModel orderGoodsModel = new OrderGoodsModel();
        BeanUtils.copyProperties(orderGoods, orderGoodsModel);
        return orderGoodsModel;
    }

    private void convertModel(OrderParent orderParent, ParentOrderModel parentOrderModel) {
        BeanUtils.copyProperties(orderParent, parentOrderModel);
    }

    private Order convert(OrderModel orderModel) {
        Order order = new Order();
        BeanUtils.copyProperties(orderModel, order);
        BeanUtils.copyProperties(orderModel.getBuyerModel(), order);
        BeanUtils.copyProperties(orderModel.getSellerModel(), order);
        return order;
    }

    private OrderDeliverDetail convert(OrderDeliverModel.OrderDeliverDetailModel orderDeliverDetailModel) {
        OrderDeliverDetail orderDeliverDetail = new OrderDeliverDetail();
        BeanUtils.copyProperties(orderDeliverDetailModel, orderDeliverDetail);
        return orderDeliverDetail;
    }

    private OrderGoods convert(OrderGoodsModel orderGoodsModel, OrderModel orderModel) {
        OrderGoods orderGoods = new OrderGoods();
        BeanUtils.copyProperties(orderGoodsModel, orderGoods);
        orderGoods.setOrderNo(orderModel.getOrderNo());
        orderGoods.setDeptId(orderModel.getSellerModel().getDeptId());
        return orderGoods;
    }

    private OrderDeliver convert(OrderDeliverModel orderDeliverModel) {
        OrderDeliver orderDeliver = new OrderDeliver();
        BeanUtils.copyProperties(orderDeliverModel, orderDeliver);
        BeanUtils.copyProperties(orderDeliverModel.getSellerModel(), orderDeliver);
        return orderDeliver;
    }

    private OrderProcessLog convert(OperateModel operateModel) {
        OrderProcessLog orderProcessLog = new OrderProcessLog();
        BeanUtils.copyProperties(operateModel, orderProcessLog);
        orderProcessLog.setOperatorName(operateModel.getOperatorName());
        orderProcessLog.setOperatorAction(operateModel.getOperatorAction().getCode());
        orderProcessLog.setCreator(operateModel.getOperator());
        orderProcessLog.setCreateName(operateModel.getOperatorName());
        orderProcessLog.setCreateTime(operateModel.getOperatorTime());
        orderProcessLog.setVersion(1);
        return orderProcessLog;
    }

    /**
     * 冻结库存
     */
    private void frozenStock(OrderGoods orderGoods, SellerModel sellerModel) {
        log.info("调用冻结库存接口开始===============start");
        MStoreFrozenRequest request = new MStoreFrozenRequest();
        request.setApplyNum(Long.valueOf(orderGoods.getGoodsNum()));
        request.setCode(orderGoods.getOrderNo());
        request.setProductId(orderGoods.getGoodsId());
        request.setFrozenFlag(true);
        RestResult<Boolean> booleanRestResult = productListApi.frozenStock(request);
    }

    /**
     * 路由分仓
     */
    private void routingPointsWarehouse(OrderDeliverModel orderDeliverModel, OrderDeliverDetail orderDeliverDetail, OperateModel operateModel) {
        MStoreQueryRequest request = new MStoreQueryRequest();
        request.setProductId(orderDeliverDetail.getGoodsId());
        List<MStoreResponse> storeResponseList = mStoreApi.listMStoreInfoByOrderInfo(request).getData();
        //匹配仓库
        List<MStoreResponse> mStoreResponseList = new ArrayList<>();
        storeResponseList.forEach(mStoreResponse -> {
            //TODO 待定以市来匹配仓库
            if (StringUtils.equals(orderDeliverModel.getReceiverCityName(), mStoreResponse.getAddressCityName())) {
                orderDeliverModel.setWarehouseId(mStoreResponse.getId());
                orderDeliverModel.setWarehouseName(mStoreResponse.getName());
                mStoreResponseList.add(mStoreResponse);
            }
        });
        if (CollectionUtils.isNotEmpty(mStoreResponseList)) {
            //实体仓大于1 通过路由分仓来匹配具体的实体仓
            if (mStoreResponseList.size() > 1) {
                //路由分仓
                List<OrderRouteSplitWarehouseResponse> orderRouteSplitWarehouseResponseList = orderRouteSplitWarehouseMapper.
                        query(new OrderRouteSplitWarehouseRequest() {{
                            setDeleteFlag(0L);
                            setStart(0);
                        }});
                orderRouteSplitWarehouseResponseList.forEach(orderRouteSplitWarehouseResponse -> {
                    //0 降低收货频率-售数量最多的实体  1代表 降低高库存风险-获取当天发货量最少的的实体仓
                    if (orderRouteSplitWarehouseResponse.getStrategy() == 0) {
                        RestResult<MStoreResponse> responseRestResult = mStoreApi.listMStoreOfMaxAvailable(new MStoreQueryRequest());
                        if (responseRestResult.getData() != null) {
                            orderDeliverModel.setWarehouseId(responseRestResult.getData().getId());
                            orderDeliverModel.setWarehouseName(responseRestResult.getData().getName());
                            return;
                        }
                    } else {
                        RestResult<MStoreResponse> responseRestResult = mStoreApi.listStoreOfMinDelivery(new MStoreQueryRequest());
                        if (responseRestResult.getData() != null) {
                            orderDeliverModel.setWarehouseId(responseRestResult.getData().getId());
                            orderDeliverModel.setWarehouseName(responseRestResult.getData().getName());
                            return;
                        }
                    }
                });
            }
        }
        //扣减库存
        MStoreSubmitRequest mStoreSubmitRequest = new MStoreSubmitRequest();
        mStoreSubmitRequest.setStoreId(orderDeliverModel.getWarehouseId());
        mStoreSubmitRequest.setCode(orderDeliverModel.getOrderNo());
        mStoreSubmitRequest.setProductId(orderDeliverDetail.getGoodsId());
        RestResult<Boolean> booleanRestResult = mStoreApi.submit(mStoreSubmitRequest);
        //成功之后更新发货仓库
        if (booleanRestResult.getData()) {
            OrderDeliver orderDeliver = convert(orderDeliverModel);
            orderDeliver.setOrderNo(orderDeliverModel.getOrderNo());
            orderDeliver.setVersion(orderDeliver.getVersion() + 1);
            orderDeliver.setUpdater(operateModel.getOperator());
            orderDeliver.setUpdaterName(operateModel.getOperatorName());
            orderDeliver.setUpdateTime(operateModel.getOperatorTime());
            orderDeliverMapper.update(orderDeliver);
        }
    }

    /**
     * 调用拼团接口
     */
    private void spellGroupInterface(OrderModel orderModel, OrderGoodsModel orderGoodsModel) {

    }

    /**
     * 发票保存接口
     */
    private void saveOrderInvoice(OrderInvoice orderInvoice) {
        orderInvoiceMapper.insert(orderInvoice);
    }
}
